﻿using System;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Principal;
using System.Web;
using EPiServer.Personalization.VisitorGroups;

namespace CriteriaPack.QueryStringCriterion
{
    [VisitorGroupCriterion(
        Category = "URL Criteria",
        Description = "Matches the request to see if it contains a querystring key with the specified value",
        //ScriptUrl = "/Templates/PublicSite/Resources/Javascript/queryStringCriterion.js",
        DisplayName = "QueryString")]
    public class QueryStringParameterCriterion : CriterionBase<QueryStringParameterModel>
    {
        public override bool IsMatch(IPrincipal principal, HttpContextBase httpContext)
        {
            NameValueCollection queryStringKeys = httpContext.Request.QueryString;

            if (Model.Condition == QueryStringValueCondition.Exists)
                return queryStringKeys.AllKeys.Contains(Model.Key);

            string keyValue = queryStringKeys[Model.Key];

            return !string.IsNullOrEmpty(keyValue)
                   && string.Equals(keyValue, Model.Value, StringComparison.CurrentCultureIgnoreCase);
        }
    }
}